# -*- coding: UTF-8 -*-
import requests
import time
import os
import pymysql
import datetime
import sys
from bs4 import BeautifulSoup

BING_URL = 'https://cn.bing.com/'
IMAGE_PATH = sys.path[0] + "/image/bing/banner"

if __name__ == '__main__':
    response = requests.get(BING_URL)
    soup = BeautifulSoup(response.text, 'lxml')
    image_node = soup.find('link', id='bgLink')
    des_node = soup.find('a', id='sh_cp')
    print("imageNode=", image_node)
    print("des = ", des_node['title'])

    if image_node is None:
        print("ImageNode not find")
        exit()

    image_url = BING_URL + image_node['href']
    image_des = des_node['title']
    read = requests.get(image_url)

    local = time.strftime("%Y_%m%d")
    if not os.path.exists(IMAGE_PATH):
        os.makedirs(IMAGE_PATH)

    file_name = "{}.jpg".format(local)
    file = os.path.join(IMAGE_PATH, file_name)

    f = open(file, 'wb')
    f.write(read.content)
    f.close()

    db_time = datetime.datetime.now()
    sql = "INSERT INTO `b_bing_banner` (`img`, `des`, `gmt_create`, `gmt_modified`) VALUES (%s, %s, %s, %s)"
    vaule = [file_name, image_des, db_time, db_time]

    db = pymysql.connect(host="host", port=3306, user="user", password="mima", db="db")
    cursor = db.cursor()
    cursor.execute(sql, vaule)
    db.commit()
